package com.macro.mall.wx.service.impl;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.wx.sdk.*;
import com.macro.mall.wx.service.WithdrawalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
public class WithdrawalServiceImpl implements WithdrawalService {
    @Autowired
    private WxBeanConfig wxBeanConfig;

    @Override
    public CommonResult withdrawal(BigDecimal amount, String openId, String ip) throws Exception {
        WxMyConfig wxMyConfig = WxMyConfig.getInstance(wxBeanConfig);
        SortedMap<String, String> paramMap = new TreeMap<String, String>();
        paramMap.put("mch_appid", wxMyConfig.getAppID());
        paramMap.put("mchid", wxMyConfig.getMchID());
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("partner_trade_no", "C" + System.currentTimeMillis());
        paramMap.put("openid", openId);
        paramMap.put("check_name", "NO_CHECK");
        paramMap.put("amount", amount.multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).toString());
        paramMap.put("desc", "提现");
        paramMap.put("spbill_create_ip", ip);
        String sign = WXPayUtil.generateSignature(paramMap, wxMyConfig.getKey(), WXPayConstants.SignType.MD5);
        paramMap.put("sign", sign);
        WXPay pay = new WXPay(wxMyConfig);
//          Map<String,String> resMap =  pay.transfer(paramMap);
        String url = "  https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        Map<String, String> resMap;
        resMap = pay.processResponseXml(pay.requestWithCert(url, paramMap, wxMyConfig.getHttpConnectTimeoutMs(),
                wxMyConfig.getHttpReadTimeoutMs()));
        String resultCode = resMap.get("result_code");
        if ("SUCCESS".equalsIgnoreCase(resultCode)) {
           return CommonResult.success(resMap);
        } else {
            String err_code = resMap.get("err_code");
            if ("SYSTEMERROR".equalsIgnoreCase(err_code)) {
                return CommonResult.failed(err_code);
            } else if ("NOTENOUGH".equalsIgnoreCase(err_code)) {
                return  CommonResult.failed(err_code);
            } else {
                return CommonResult.failed("调用微信提现接口未知错误，请联系管理员！");
            }
        }
    }
}